package com.my.assembly.handler;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import com.my.assembly.bridge.BridgeHandler;
import com.my.assembly.bridge.CallBackFunction;
import com.my.assembly.config.Config;
import com.my.assembly.http.HttpClient;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * <pre>
 *     author : wuxiaoqi
 *     e-mail : 1321972760@qq.com
 *     time   : 2018/12/26
 *     desc   : 微信登录
 *     version: 1.0
 * </pre>
 */
public class WeChatLoginHandler implements BridgeHandler {

    private Activity mContext;
    private IWXAPI api;

    private CallBackFunction mCallBackFunction;

    public WeChatLoginHandler(Activity activity, IWXAPI api) {
        this.mContext = activity;
        this.api = api;
    }

    @Override
    public void handler(String data, CallBackFunction function) {
        this.mCallBackFunction = function;
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "com.new.youyiku";
        api.sendReq(req);
    }

    public void login(String code) {
        OkHttpClient client = HttpClient.getInstance().getClient();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "code=" + code);
        Request request = new Request.Builder()
                .url(Config.base_url + "/WebApp/WeChatLogin/WeChatLogin")
                .post(body)
                .addHeader("DEVICEINFO", "JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        mCallBackFunction.onCallBack(e.getMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String s = response.body().string();
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        mCallBackFunction.onCallBack(s);
                    }
                });
            }
        });
    }
}
